package midone.exchangeskill.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * 运行时权限申请工具
 * Created by 想法的猫 on 2016/10/8.
 */

public class PermissionUtil {
    /**
     * 是否需要授权
     *
     * @param context
     * @param permission
     * @return
     */
    public static boolean checkPermission(Context context, String permission) {
        return ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 是否需要授权
     *
     * @param context
     * @param permissions 需要检查的权限列表
     * @param requestCode 如果需要申请权限 回调code
     * @return
     */
    public static boolean checkPermission(Activity context, String[] permissions, int requestCode) {
        List<String> permissionDenied = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(context, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                permissionDenied.add(permissions[i]);
            }
        }
        if (permissionDenied.size() > 0) {
            ActivityCompat.requestPermissions(context, permissionDenied.toArray(new String[]{}), requestCode);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 权限是否都已经授权
     *
     * @param grantResults
     * @return
     */
    public static boolean isAllGranted(int[] grantResults) {
        if (grantResults.length == 0) {
            return false;
        }
        boolean isAllGranted = true;
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                isAllGranted = false;
                break;
            }
        }
        return isAllGranted;
    }
}
